package com.zboot.zbootadmin.common.security.service;



import com.zboot.zbootadmin.common.config.redis.RedisCache;
import com.zboot.zbootadmin.common.constant.Constants;
import com.zboot.zbootadmin.common.exception.CustomException;
import com.zboot.zbootadmin.common.exception.user.CaptchaException;
import com.zboot.zbootadmin.common.exception.user.CaptchaExpireException;
import com.zboot.zbootadmin.common.exception.user.UserPasswordNotMatchException;
import com.zboot.zbootadmin.common.security.LoginUser;
import com.zboot.zbootadmin.common.utils.MessageUtils;
import com.zboot.zbootadmin.project.system.log.entity.SysLogninIformation;
import com.zboot.zbootadmin.project.system.log.service.SysLoginInformationService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * 登录校验方法
 * 
 * @author zyt
 */
@Component
public class SysLoginService
{

    private static final Logger log = LoggerFactory.getLogger(UserDetailsServiceImpl.class);

    @Autowired
    private TokenService tokenService;

    @Resource
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private MessageUtils messageUtils;

    @Autowired
    private SysLoginInformationService loginInformationService;


    /**
     * 登录验证
     * 
     * @param username 用户名
     * @param password 密码
     * @param  code  验证码
     * @param uuid 唯一标识
     * @return 结果
     */
    public String login(String username, String password, String code, String uuid)
    {
        String verifyKey = Constants.CAPTCHA_CODE_KEY + uuid;
        String captcha = redisCache.getCacheObject(verifyKey);
        redisCache.deleteObject(verifyKey);
        if (captcha == null)
        {
            loginInformationService.insert(MessageUtils.get("user.password.overtime"),Constants.FAIL, username);
            return MessageUtils.get("user.password.overtime");
        }
        if (!code.equalsIgnoreCase(captcha))
        {
            loginInformationService.insert(MessageUtils.get("user.captcha.error"),Constants.FAIL, username);
            return MessageUtils.get("user.captcha.error");

        }
        // 用户验证
        Authentication authentication = null;

        try
        {
            // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
            authentication = authenticationManager
                    .authenticate(new UsernamePasswordAuthenticationToken(username, password));
        }
        catch (Exception e)
        {
            if (e instanceof BadCredentialsException)
            {
                loginInformationService.insert( MessageUtils.get("user.password.not.match"),Constants.FAIL, username);
                return MessageUtils.get("user.password.not.match");
            }
            else
            {
                loginInformationService.insert( "未知错误",Constants.FAIL, username);
                throw new CustomException(e.getMessage());
            }
        }
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        loginInformationService.insert(  MessageUtils.get("user.login.success"),Constants.SUCCESS, username);
        // 生成token
        return tokenService.createToken(loginUser);
    }
}
